<template>
  <div class="app-container">
    <el-form
      ref="queryParams"
      :model="queryParams"
      size="small"
      label-suffix=":"
      label-width="auto"
    >
      <el-row :gutter="10">
        <el-col :span="1.5">
          <el-form-item :label="$t('destructionLang.destructionNum')" prop="destructionNum">
            <el-input
              v-model="queryParams.destructNo"
              :placeholder="$t('pleaseEnter') + $t('destructionLang.destructionNum') + '，' + $t('MultipleSpacesSeparated')"
              clearable
              filterable
              style="width: 300px"
            />
          </el-form-item>
        </el-col>
        <el-col :span="1.5">
          <el-form-item :label="$t('destructionLang.destructionStatus')" prop="status">
            <el-select
              v-model="queryParams.status"
              :placeholder="$t('pleaseSelect')"
              clearable
              style="width: 300px"
            >
              <el-option
                v-for="item in destructStatusOptions"
                :key="item.value"
                :value="item.value"
                :label="$t('statusLang.' + item.title)"
              />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="10">
        <el-col :span="1.5">
          <el-form-item :label="$t('destructionLang.sku')" prop="sku">
            <el-input
              v-model="queryParams.sku"
              :placeholder="$t('pleaseEnter') + $t('goodsSKULang.skuCode')"
              clearable
              filterable
              style="width: 300px"
            />
          </el-form-item>
        </el-col>
        <el-col :span="1.5">
          <el-form-item :label="$t('depotLang.depot')" prop="depotId">
            <el-select
              v-model="queryParams.depotId"
              :placeholder="$t('pleaseSelect')"
              clearable
              style="width: 300px"
            >
              <el-option
                v-for="item in depotListAllStatusList"
                :key="item.value"
                :value="item.value"
                :label="$t(item.title)"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="1.5">
          <el-form-item
            :label="$t('harvestLang.customerName')"
            prop="customerId"
          >
            <el-select
              v-model="queryParams.customerId"
              :placeholder="$t('backOrderLang.userName')"
              clearable
              filterable
              style="width: 300px"
            >
              <el-option
                v-for="item in customerOptionList"
                :key="item.value"
                :value="item.value"
                :label="item.title"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="primary"
            size="mini"
            icon="el-icon-search"
            @click="handleQuery"
          >
            {{ $t("query") }}
          </el-button>
          <el-button
            type="primary"
            size="mini"
            icon="el-icon-refresh-left"
            @click="handleReset"
          >
            {{ $t("reset") }}
          </el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="primary"
            size="mini"
            icon="el-icon-plus"
            @click="handleAdd"
          >
            {{ $t("add") }}</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button type="primary" size="mini" @click="exportToExcel()">
            {{ $t("goodsSKULang.imports") }}
          </el-button>
        </el-col>
      </el-row>
      <el-row :gutter="10" />
    </el-form>
    <el-table
      ref="table"
      v-loading="loading"
      :data="tableData"
      border
      class="mt-10"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column
        :label="$t('tableIndex')"
        type="index"
        :index="indexAdd"
        align="center"
        width="100"
      />
      <el-table-column
        :label="$t('destructionLang.destructionInfo')"
        prop="destroyNo,status,destroyTotalNum"
        align="left"
        min-width="150"
      >
        <template slot-scope="scope">
          <p>
            {{ $t("destructionLang.destructionNum") + ":" }}
            <span>{{ scope.row.destroyNo }}</span>
          </p>
          <p>
            {{ $t("destructionLang.destructionStatus") + ":" }}
            <span>{{ $t("statusLang." + getTitleByValue(destructStatusOptions, scope.row.status)) }}</span>
          </p>
          <p>
            {{ $t("destructionLang.skuDestructionAllNum") + ":" }}
            <span>{{ scope.row.destroyTotalNum }}</span>
          </p>
        </template>
      </el-table-column>
      <el-table-column
        :label="$t('destructionLang.source')"
        prop="source"
        align="center"
        min-width="150"
      />
      <el-table-column
        :label="$t('destructionLang.warehouseCode')"
        prop="depotName"
        align="left"
        min-width="150"
      >
        <template slot-scope="scope">
          <p>
            <span>{{ scope.row.depotCode + '[' + scope.row.depotName + ']' }}</span>
          </p>
        </template>
      </el-table-column>
      <el-table-column
        :label="$t('destructionLang.user')"
        prop="customerName"
        align="left"
        min-width="150"
      >
        <template slot-scope="scope">
          <p>
            <span>{{ scope.row.customerId + '[' + scope.row.customerName + ']' }}</span>
          </p>
        </template>
      </el-table-column>
      <el-table-column
        :label="$t('destructionLang.date')"
        prop="gmtCreated,destroyTime,gmtModified"
        align="left"
        min-width="150"
      >
        <template slot-scope="scope">
          <p>
            {{ $t("destructionLang.createDate") + ":" }}
            <span>{{ scope.row.gmtCreated }}</span>
          </p>
          <p>
            {{ $t("destructionLang.destructionDate") + ":" }}
            <span>{{ scope.row.destroyTime }}</span>
          </p>
          <p>
            {{ $t("destructionLang.lastEditDate") + ":" }}
            <span>{{ scope.row.gmtModified }}</span>
          </p>
        </template>
      </el-table-column>
      <el-table-column
        :label="$t('destructionLang.operator')"
        prop="createdUser,destroyUser,modifiedUser"
        align="left"
        min-width="150"
      >
        <template slot-scope="scope">
          <p>
            {{ $t("cutOffOrderLang.creator") + ":" }}
            <span>{{ scope.row.createdUser
            }}</span>
          </p>
          <p>
            {{ $t("destructionLang.destructor") + ":" }}
            <span>{{ scope.row.destroyUser
            }}</span>
          </p>
          <p>
            {{ $t("problemItemLang.lastEditor") + ":" }}
            <span>{{ scope.row.modifiedUser
            }}</span>
          </p>
        </template>
      </el-table-column>
      <el-table-column
        :label="$t('operation')"
        width="100"
        align="center"
        fixed="right"
      >
        <template slot-scope="scope">
          <el-button type="text" @click="handleDetail(scope.row)">
            {{ $t("info") }}
          </el-button>
          <el-button v-if="scope.row.status == 1" type="text" @click="handleDelete(scope.row)">
            {{ $t("delete") }}
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 页码 -->
    <el-row type="flex" justify="end" align="middle" style="height: 60px">
      <el-pagination
        :total="total"
        layoout="total,prev,pager,next"
        :current-page="queryParams.pageNo"
        :page-size="queryParams.pageSize"
        @current-change="pageNoChange"
      />
    </el-row>
    <!-- 详情弹层 -->
    <DetailBaseForm
      v-model="detailParams.id"
      :visible.sync="detailDialog"
      :title="title"
      :operation="detailParams.operation"
      @close="close"
    />
    <!-- 新增弹层 -->
    <AddBaseForm
      v-model="addParams.id"
      :visible.sync="addDialog"
      :title="title"
      :operation="addParams.operation"
      @close="closeAdd"
    />
  </div>
</template>

<script>
import DetailBaseForm from './components/detail.vue'
import AddBaseForm from './components/add-form.vue'
import { destructStatusOptionDict } from '@/utils/dictData'
import { getDictOptionList, getTitleByValue } from '@/utils/dictUtils'
import { getDepotList } from '@/api/business/depotManage/depot'
import { deleteDestruct, getDestructPageList, exportList } from '@/api/business/operateManage/destruct'
import { getCustomerNameList } from '@/api/business/inventoryManage/inventory'
import XLSX from 'xlsx';
export default {
  name: 'Depot',
  components: { DetailBaseForm, AddBaseForm },
  data() {
    return {
      total: 0,
      loading: false,
      depotListAllStatusList: [], // 仓库列表
      queryParams: {
        destructNo: null,
        status: null,
        depotId: null,
        sku: null,
        customerId: null,
        pageNo: 1,
        pageSize: 10
      },
      customerOptionList: [], // 客户名称下拉
      tableData: [], // 列表
      getTitleByValue: getTitleByValue,
      destructStatusOptions: getDictOptionList(destructStatusOptionDict), // 状态
      detailParams: {
        id: null,
        operation: 0
      },
      addParams: {
        id: null,
        operation: 0
      },
      detailDialog: false,
      addDialog: false,
      title: ''
    }
  },
  created() {
    this.getDestructPageList()
    this.getDepotListAllStatus()
    this.getCustomerNameList()
  },
  methods: {
    // 重置
    async handleReset() {
      this.queryParams = {
        pageNo: 1,
        pageSize: 10,
        destructNo: null,
        status: null,
        depotId: null
      }
      this.getDestructPageList()
    },
    // 查询
    async handleQuery() {
      this.queryParams.pageNo = 1
      this.getDestructPageList()
    },
    // 获取数据列表
    async getDestructPageList() {
      console.log(this.queryParams.destructNo, 'this.queryParams.destructNo')
      if (this.queryParams.destructNo) {
        if (this.queryParams.destructNo.includes(' ')) {
          this.queryParams.destroyNos = []
          // 使用空格将 destroyNo 分隔成数组
          this.queryParams.destroyNos = this.queryParams.destructNo.split(' ')
          this.queryParams.destroyNo = null
        } else {
          this.queryParams.destroyNo = this.queryParams.destructNo
          this.queryParams.destroyNos = []
        }
      } else {
        this.queryParams.destroyNo = null
        this.queryParams.destroyNos = null
      }
      this.loading = true
      const res = await getDestructPageList({ ...this.queryParams })
      if (res.data.destroyOrderOverseaDTOList) {
        this.tableData = res.data.destroyOrderOverseaDTOList
        this.total = res.data.totalRowNum
      } else {
        this.tableData = []
        this.total = 0
      }
      this.loading = false
    },
    // 仓库下拉列表
    async getDepotListAllStatus() {
      const { data } = await getDepotList()
      this.depotListAllStatusList = data
      console.log(data)
    },
    // 新增
    async handleAdd() {
      this.addParams.operation = 1
      this.title = this.$t('add')
      this.addDialog = true
    },
    // 查看
    async handleDetail(row) {
      this.detailParams.operation = 0
      this.detailParams.id = row.destroyOrderOverseaId
      this.title = this.$t('info')
      this.detailDialog = true
      // setTimeout(() => {
      //   this.detailDialog = true
      // }, 400)
    },
    // 删除
    async handleDelete(row) {
      const flag = await this.$confirm(
        this.$t('destructionLang.deleteHint'),
        this.$t('hint'),
        {
          confirmButtonText: this.$t('confirm'),
          cancelButtonText: this.$t('cancel'),
          type: 'warning'
        }
      ).catch((err) => err)
      if (flag === 'cancel') return
      const res = await deleteDestruct({
        destroyOrderOverseaId: row.destroyOrderOverseaId
      })
      if (res && res.returnCode === 10000) {
        this.$message({
          type: 'success',
          message: this.$t('handleSuccess')
        })
        this.getDestructPageList()
      }
    },
    // 关闭弹出层
    close() {
      this.detailParams.id = null
      this.detailParams.operation = 0
      this.detailDialog = false
    },
    // 关闭弹出层
    closeAdd() {
      this.addParams.id = null
      this.addParams.operation = 0
      this.addDialog = false
      this.getDestructPageList()
    },
    // 切换页码
    pageNoChange(newPage) {
      this.queryParams.pageNo = newPage
      this.getDestructPageList()
    },
    indexAdd(index) {
      // console.log(index)
      const page = this.queryParams.pageNo // 当前页码
      const pagesize = this.queryParams.pageSize // 每页条数
      return index + 1 + (page - 1) * pagesize
    },
    // 获取客户名称下拉
    async getCustomerNameList() {
      const { data } = await getCustomerNameList()
      this.customerOptionList = data
    },
    //  批量导出
    async exportToExcel() {
      const selectedRows = this.$refs.table.store.states.selection;
      const destroyOrderOverseaId = selectedRows.map(row => row.destroyOrderOverseaId);
      if (destroyOrderOverseaId.length === 0) {
        this.$message.warning('请选择需要导出的数据');
        return;
      }
      const res = await exportList(destroyOrderOverseaId);

      // 创建工作簿
      const workbook = XLSX.utils.book_new();

      // 构建表头
      const header = ['销毁单号', '状态', 'sku 销毁总数', '来源', '仓库', '客户名称', '创建日期', '销毁日期', '最后修改日期', '创建人', '销毁人', '最后修改人', 'sku', '产品名称', '库龄(天)', '库位', '销售数量', '实际销售数量', '备注'];

      const dataRows = [];
      let index = 0;
      res.data.forEach(item => {
        const statusMap = {
          1: '待销毁',
          2: '部分销毁',
          3: '全部销毁'
        };
        const mainDataRow = [
          item.destroyNo,
          statusMap[item.status] || '',
          item.destroyTotalNum,
          item.source,
          item.depotCodeAndName,
          item.customerIdAndName,
          item.gmtCreateDate,
          item.destroyTimes,
          item.gmtModifiedDate,
          item.creatorName,
          item.destroyName,
          item.modifierName
        ];
        if (item.destroyOrderDetails && item.destroyOrderDetails.length > 0) {
          let firstRow = true;
          item.destroyOrderDetails.forEach(destroyOrderDetail => {
            const extendedRow = firstRow ? [...mainDataRow] : new Array(mainDataRow.length).fill('');
            extendedRow.push(
              destroyOrderDetail.skuCode,
              destroyOrderDetail.declaredName,
              destroyOrderDetail.daysAge,
              destroyOrderDetail.locationCode,
              destroyOrderDetail.destroyQty,
              destroyOrderDetail.actualDestroyQty,
              destroyOrderDetail.remark
            );
            dataRows[index++] = extendedRow;
            firstRow = false;
          });
        } else {
          dataRows[index++] = [...mainDataRow];
        }
      });

      const worksheet = XLSX.utils.aoa_to_sheet([header, ...dataRows]);
      XLSX.utils.book_append_sheet(workbook, worksheet, 'Sheet1');

      const columnWidths = {};
      worksheet['!cols'] = [];
      header.forEach((colName, colIndex) => {
        const maxLength = dataRows.reduce((max, row) => Math.max(max, (row[colIndex] || '').toString().length), 0);
        columnWidths[colIndex] = maxLength < 10 ? 10 : maxLength;
        worksheet['!cols'].push({ wch: columnWidths[colIndex] });
      });

      const excelData = XLSX.write(workbook, { bookType: 'xlsx', type: 'binary' });
      const blob = new Blob([new Uint8Array([...excelData].map(c => c.charCodeAt(0)))], { type: 'application/octet-stream' });
      const url = URL.createObjectURL(blob);
      const link = document.createElement('a');
      link.href = url;
      link.download = '销毁单数据详情.xlsx';
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
      URL.revokeObjectURL(url);
    },
  },

}
</script>

<style scss="lang" scoped></style>
